﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using ZhCun.Utils.Helpers;
using ZhCun.WebUtils.Configs;

namespace ZhCun.WebUtils
{
    public class SwaggerOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<OpenApiParameter>();
            }

            UserAuthorizeAttribute authAttr = context.MethodInfo.GetCustomAttribute<UserAuthorizeAttribute>();
            if (authAttr == null)
            {
                authAttr = context.MethodInfo.ReflectedType.GetCustomAttribute<UserAuthorizeAttribute>();
            }

            if (authAttr?.IsAuth == true)
            {
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = CommonConfig.THIS.TokenName,
                    In = ParameterLocation.Header,
                    Required = true,
                    Description = "Token 字符出啊",
                    AllowEmptyValue = false
                });
            }

            BodyEncryptFilterAttribute enAttr = context.MethodInfo.GetCustomAttribute<BodyEncryptFilterAttribute>();
            if (authAttr == null)
            {
                enAttr = context.MethodInfo.ReflectedType.GetCustomAttribute<BodyEncryptFilterAttribute>();
            }
            if (enAttr?.IsEncrypt == true)
            {
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = CommonConfig.THIS.BodyEncryptKeyName,
                    In = ParameterLocation.Header,
                    Required = true,
                    Description = "body加密密钥",
                    AllowEmptyValue = true
                });
            }

        }

    }
}
